import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;


public class HeapMain {
	private static int n, h;
	private static RepSel<Integer> repsel;
	
	public static void main(String[] args) {
		InvoerScanner invoer = new InvoerScanner();
		n = invoer.getInt("Geef N: ");
		h = invoer.getInt("Geef H: ");
		
//		while(h >= n/2) {
//			System.out.println("H mag niet groter of gelijk zijn aan de helft van N!");
//			h = invoer.getInt("Kies een nieuwe H: ");
//		}
		
		repsel = new RepSel<Integer>(h);
		repsel.replacementSelection(buildArray(n));
		
		writeStatistics();
		
	}
	
	private static Integer[] buildArray(int size) {
		Integer[] array = new Integer[size];
		
		for(int i = 0; i < size; i++) {
			array[i] = (int) ((Math.random() * (size *2)) + 1);
		}
		return array;
	}
	
	private static void writeStatistics() {
		ArrayList<ArrayList<Integer>> runs = repsel.getRuns();
		double mean = calculateMean();
		double stdv = calculateStdv(mean);
		
		try {
			BufferedWriter w = new BufferedWriter(new FileWriter("stats.txt"));
			
			w.write("--------------------------- \n");
			w.write("-      STATISTIEKEN       - \n");
			w.write("--------------------------- \n  \n");
			
			w.write("N: " + n + " \n");
			w.write("H: " + h + " \n  \n");

			w.write("Gemmiddelde: " + mean + " \n");
			w.write("Standaard deviatie: " + stdv + " \n \n");

			w.write("Aantal runs: " + runs.size() + " \n \n");
			
			w.write("\nCorrectheid van de runs calculeren: \n");
			boolean correct = true;
			for(ArrayList<Integer> singleRun: runs) {
				for(int i = 0; i < singleRun.size() -1; i++) {
					if(singleRun.get(i) > singleRun.get(i + 1)) {
						correct = false;
					}
				}
			}
			if(!correct) {
				w.write("E�n of meer runs is incorrect!");
			} else {
				w.write("Alle runs zijn correct!");
			}
			w.close();
			System.out.println("STATS WRITTEN INTO stats.txt");
		}  catch( Exception e ) {
			System.err.println( "FAILED: " + e );
			e.printStackTrace();
		}
	}
	
	private static double calculateMean() {
		ArrayList<ArrayList<Integer>> runs = repsel.getRuns();
		double total = 0;
		for(ArrayList<Integer> singleRun : runs) {
			total += singleRun.size();
		}
		
		return (total / runs.size());
	}
	
	private static double calculateStdv(double mean) {
		ArrayList<ArrayList<Integer>> runs = repsel.getRuns();
		
		double total = 0;
		for(ArrayList<Integer> singleRun : runs) {
			total += (singleRun.size() * singleRun.size());
		}
		
		return Math.sqrt(total / runs.size() - mean * mean);
	}
}
